package com.lb.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.lang3.StringUtils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

/**
 * @author jzhang
 * @version 1.0
 * @date 2022-11-23 11:21
 */
public class ReadFile {
    public static void main(String[] args) throws FileNotFoundException {
        String result = FileUtil.readString("D:\\\\clinical_word_hpo_statistic.json", CharsetUtil.charset("UTF-8"));
        JSONObject object = JSONUtil.toBean(result, JSONObject.class);
        File file = new File("D:\\\\clinical_word_hpo_statistic.sql");
        PrintStream ps = new PrintStream(new FileOutputStream(file,true));
        object.forEach((k, v) -> {
            JSONObject o = (JSONObject) v;
            List<String> list = new ArrayList<>();
            o.forEach((k2,v2) -> {
                String v3 = k2.substring(0, k2.indexOf("("));
                list.add("\"" + v3 + "\"");
            });
            String id = randomUUID("mh");
            String sql = "INSERT INTO merlionw.medical_hpo (id, medical_term, hpo, create_by, create_time, update_by, update_time) SELECT '"+id+"', '" + k + "', '"+Arrays.toString(list.toArray())+"'::jsonb, 'SYSTEM', current_timestamp, NULL, NULL WHERE NOT EXISTS(SELECT 1 FROM merlionw.medical_hpo WHERE id = '"+id+"');";
            ps.append(sql);
            ps.append("\r\n");
        });
        System.out.println("sql生成成功！");
        ps.close();
    }

    private static AtomicInteger aiSeq4 = new AtomicInteger(0);
    public static String randomUUID(String prefix) {
        // part1 prefix
        if (StringUtils.isBlank(prefix)) {
            prefix = "";
        }

        // part2 currentTimeMillis
        long currentTimeMillis = System.currentTimeMillis();

        // part3 host order
        Integer hostOrder = 1;

        // part4 sequence
        int nextInt = aiSeq4.incrementAndGet();
        if (nextInt == 9999) {
            aiSeq4.compareAndSet(9999, 0);
        }
        String seq4 = StringUtils.leftPad(Integer.toString(nextInt), 4, "0");

        String resultString = prefix + currentTimeMillis + hostOrder + seq4;

        return resultString;
    }
}
